package com.proj.controller;

import com.proj.bean.User;
import com.proj.bean.Useraddress;
import com.proj.dao.ManagerDao;
import com.proj.service.IUserService;
import com.proj.util.SYS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@RequestMapping("user")
@Controller
public class UserController {

    @Autowired
    IUserService userService;

    @Autowired
    ManagerDao managerDao;


    @ResponseBody
    @RequestMapping("getbyname")
    public User getUserByUsername(String name) {
        return userService.getUserByUsername(name);
    }

    @ResponseBody
    @RequestMapping("getbyid")
    public User getuserById(HttpSession session) {
        return userService.getuserById(((User) session.getAttribute(SYS.SHOPPING_LOGIN_USER)).getId());
    }

    @ResponseBody
    @RequestMapping("getaddress")
    public List<Useraddress> getaddress(HttpSession session) {
        int userid = SYS.getLoginUserID(session);
        return userService.getaddress(userid);
    }


    @ResponseBody
    @RequestMapping("getaddressbyid")
    public Useraddress getAddressById(int id) {
        return userService.getAddressById(id);
    }

    @ResponseBody
    @RequestMapping("addaddress")
    public int add(Useraddress address, HttpSession session) {
        address.setUserid(SYS.getLoginUserID(session));
        return userService.add(address);
    }

    @ResponseBody
    @RequestMapping("editaddress")
    public int edit(Useraddress address) {
        System.out.println(address);
        return userService.edit(address);
    }

    @ResponseBody
    @RequestMapping("deleteaddress")
    public int delete(int id) {
        return userService.delete(id);
    }

    @ResponseBody
    @RequestMapping("defaultaddress")
    public int setDefault(int id,HttpSession session) {
        int userid = SYS.getLoginUserID(session);
        return userService.setDefault(id,userid);
    }

    @ResponseBody
    @RequestMapping("new")
    public int setDefault(User user) {
        String hexpass=SYS.digest(user.getPassword());
        user.setPassword(hexpass);
        return userService.newuser(user);
    }

    @ResponseBody
    @RequestMapping("updateUserById")
    public int updateUserById(User user, HttpSession session) {
        user.setId(SYS.getLoginUserID(session));
        user.setPassword(null);
        user.setName(null);
        System.out.println("update:"+user);
        return managerDao.editUser(user);
    }

    @ResponseBody
    @RequestMapping("newpass")
    public int newpass(String password, HttpSession session) {
        password=SYS.digest(password);
        Integer userid = SYS.getLoginUserID(session);
        return userService.newpass(password,userid);
    }

}
